import pool from "@/lib/db";
import { NextResponse } from "next/server";

export async function GET() {
  const connection = await pool.getConnection();
  
  try {
    // 开启事务
    await connection.beginTransaction();
    
    // 先删除有外键约束的表
    console.log('开始删除表...');
    const tablesToDrop = [
      'user',
      'cusomer',
      'department',
      // ... 其他表
    ];
 
    // 删除旧表
    for (const table of tablesToDrop) {
      await connection.execute(`DROP TABLE IF EXISTS ${table}`);
    }
 
    // 创建用户表
    await connection.execute(`
      CREATE TABLE user (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) NOT NULL UNIQUE,
        password VARCHAR(64) NOT NULL,
        email VARCHAR(255) NOT NULL UNIQUE,
        phone VARCHAR(20) UNIQUE,
        avatar VARCHAR(255) DEFAULT '/avatars/user.jpg',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);
 
    // ... 创建其他表 ...
 
    // 提交事务
    await connection.commit();
    
    return NextResponse.json({ 
      status: 'success',
      message: '数据库表创建成功'
    });
  } catch (error) {
    // 如果出错，回滚事务
    await connection.rollback();
    return NextResponse.json({ 
      status: 'error',
      message: '数据库表创建失败',
      error: error instanceof Error ? error.message : String(error)
    }, { status: 500 });
  } finally {
    // 释放连接
    connection.release();
  }
}